//
//  ZJKComposeViewController.swift
//  MicroBlog
//
//  Created by VAD on 16/4/25.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit

import SVProgressHUD

class ZJKComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        self.textView.becomeFirstResponder()
    }
    
    
    //返回按钮点击方法
    
    @objc private func back(){
        
        self.textView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //选择图片方法
    private func selectPicture(){
        
        let vc = UIImagePickerController()
        
        vc.delegate = self
        
        self.presentViewController(vc, animated: true, completion: nil)
    }
    
    // MARK: - 发送微博方法
    
    @objc private func send(){
        if pictureView.hidden{
            update()
        }else{
            upload()
        }
    }
    
    //发送文字微博
    
    private func update(){
        
        // 请求地址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        // 请求参数
        let params = [
            
            "access_token": ZJKUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "status": textView.text!
        ]
        
        // 发送请求
        HMNetworkTools.sharedTools.request(HMRequestMethod.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            if error != nil {
                
                print("发送失败\(error)")
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    /// 发送图片微博
    private func upload(){
        
        // 请求地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        // 请求参数
        let params = [
            "access_token": ZJKUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "status": textView.text!,
        ]
        let data = UIImagePNGRepresentation(self.pictureView.images.first!)!
        HMNetworkTools.sharedTools.upload(urlString, parameters: params, datas: ["pic": data]) { (responseObject, error) -> () in
            if error != nil {
                print("发送失败\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    
     private func switchKeyboard(){
        
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        // 控制器告诉 toolBar 当前显示的是什么键盘
        composeToolBar.isSystemKeyboard = textView.inputView == nil
        // 重新加载输入的视图
        textView.reloadInputViews()
        if !textView.isFirstResponder() {
            textView.becomeFirstResponder()
        }

    }

    //键盘frame改变要通知执行的方法
    
    @objc private func keyboardChangeFrame(noti: NSNotification){
        
        
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        print(endFrame)
        
        // 调整toolBar的位置
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(endFrame.origin.y - SCREENH)
        }
        
        //执行动画
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    
    // MARK: - 懒加载控件
    
    private lazy var emoticonKeyboard: ZJKEmoticonKeyboard = {
        let keyboard = ZJKEmoticonKeyboard()
        keyboard.frame.size = CGSize(width: SCREENW, height: 216)
        return keyboard
    }()
    
    private lazy var pictureView: ZJKComposePictureView = {
       
        let pictureView = ZJKComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        pictureView.selectedPictureClosure = {[weak self] in
            self?.selectPicture()
            
        }
        return pictureView
    }()
    
    private lazy var composeToolBar: ZJKComposeToolBar = {
        let composeToolBar = ZJKComposeToolBar(frame: CGRectZero)
        
        // 设置里面子控件点击要执行的闭包
        composeToolBar.buttonClickClosure = {[weak self] (type: ZJKComposeToolBarButtonType) in
            print(type)
            
            switch type {
            case .Picture:
                self?.selectPicture()
                break
            case .Mention:
                break
            case .Trend:
                break
            case .Emoticon:
                self?.switchKeyboard()
                break
            case .Add:
                break

            }
        }
        
        return composeToolBar
    }()
    
    //文本视图
    private lazy var textView: ZJKTextView = {
        
        let textView = ZJKTextView()
        
        textView.delegate = self
        
        textView.placeholder = "听说吴尔希和汪康再一起的简称叫尔康~~~~"
        
        textView.font = UIFont.systemFontOfSize(16)
        
        // 拖动的时候消失键盘 (系统会弹出警告)
        textView.keyboardDismissMode = .OnDrag
        
        // 开启垂直方向的弹簧效果
        textView.alwaysBounceVertical = true
       
        return textView
    }()
    //右边按钮
    private lazy var rightButton: UIButton = {
        let rightButton = UIButton(textColor: UIColor.whiteColor(), fontSize: 14)
        
        rightButton.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside)
        rightButton.setTitle("发送", forState: UIControlState.Normal)
        // 设置不同状态下的背景图
        rightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置不同状态的文字颜色
        rightButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        
        rightButton.frame.size = CGSize(width: 45, height: 28)
        // 不启用
        // rightButton.enabled = false
        return rightButton
    }()
    
    //标题视图
    private lazy var titleView: UILabel = {
        
        let titleView = UILabel()
        
        // 指定行数
        titleView.numberOfLines = 0
        
        // 指定字体的颜色
        titleView.textColor = UIColor.blackColor()
        
        titleView.font = UIFont.systemFontOfSize(14)
        
        // 设置文字居中
        titleView.textAlignment = .Center
        
        if let name = ZJKUserAccountViewModel.sharedViewModel.account?.name {
            
            let text = "发微博\n\(name)"
            
            // 求出name所在的字符串范围
            let range = (text as NSString).rangeOfString(name)
            
            let attrText = NSMutableAttributedString(string: text)
            
            // 添加属性: 参数1：属性列表（字典类型），参数2：添加的范围
            attrText.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(20), NSStrokeWidthAttributeName: 2, NSStrokeColorAttributeName: UIColor.redColor()], range: range)
            
            // 设置富文本
            titleView.attributedText = attrText
            // titleView.text = text
        }else{
            
            titleView.text = "发微博"
        }
        
        // 自适定大小 --> 内容多大，控件就多大
        titleView.sizeToFit()
        
        return titleView
    }()

}


extension ZJKComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 关闭当前界面
        let img = image.scaleToWidth(600)
        
        let data = UIImagePNGRepresentation(img)
        
        data?.writeToFile("/Users/a123/Desktop/\(random()/3).png", atomically: true)
        
        pictureView.addImage(img)
        
        picker.dismissViewControllerAnimated(true, completion: nil)

    }
}


extension ZJKComposeViewController{
    
    // 设置导航栏的内容
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
        
        navigationItem.titleView = titleView
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    // 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        //添加控件
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        
        textView.addSubview(pictureView)
        
        // 添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(10)
            make.top.equalTo(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        
         NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }

   
}

extension ZJKComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
